/*
 * Copyright (C) 2017-2019 Dremio Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dremio.plugins.elastic;

import java.io.IOException;

import javax.inject.Inject;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Context;

import org.glassfish.jersey.message.MessageBodyWorkers;

import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;

/**
 * Adds authentication headers generated by AWS4Signer to requests to support elasticsearch on AWS.
 */
public class ElasticsearchRequestClientFilter implements ClientRequestFilter {

  protected static final String REGION_NAME = "aws.region.name";
  private static final String SERVICE_NAME = "es";
  private final AWS4Signer signer;
  private final AWSCredentialsProvider awsCredentialsProvider;
  private final MessageBodyWorkers workers;

  @Inject
  public ElasticsearchRequestClientFilter(final InjectableAWSCredentialsProvider awsCredentialsProvider,
                                          @Context final Configuration configuration,
                                          @Context final MessageBodyWorkers workers) {
    this.awsCredentialsProvider = awsCredentialsProvider;
    this.signer = new AWS4Signer();
    this.signer.setRegionName((String) configuration.getProperty(REGION_NAME));
    this.signer.setServiceName(SERVICE_NAME);
    this.workers = workers;
  }

  @Override
  public void filter(ClientRequestContext clientRequestContext) throws IOException {
    // Creates AWSRequest from clientRequestContext.
    AWSRequest request = new AWSRequest(signer.getServiceName(), clientRequestContext, workers);
    // Uses AWS4Signer.sign to generate the authentication headers for clientRequestContext.
    signer.sign(request, awsCredentialsProvider.getCredentials());
  }
}
